package com.heba.fragment.product;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.FmPagerAdapter;
import com.heba.adapter.QuickAdapter;
import com.heba.adapter.diary.DiaryListRecyclerAdapter;
import com.heba.adapter.diary.callback.DiaryItemListener;
import com.heba.bean.ItemShopObject;
import com.heba.bean.ShareObject;
import com.heba.bean.diary.ItemDiaryDetailObject;
import com.heba.bean.feature.ItemFeatureCategoryObject;
import com.heba.bean.feature.ItemFeatureProductObject;
import com.heba.bean.user.UserAddressObject;
import com.heba.config.CommonConfig;
import com.heba.dialog.MyProgressDialog;
import com.heba.event.MessageEvent;
import com.heba.event.ShopListEvent;
import com.heba.event.ShopMessageEvent;
import com.heba.fragment.BaseFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.ScanActivity;
import com.heba.greenmulu.businesslist.BusinessAddNewAddressActivity;
import com.heba.greenmulu.businesslist.BusinessEditAddressActivity;
import com.heba.greenmulu.diary.ItemDiarySearchNewActivity;
import com.heba.greenmulu.scan.ItemProductCategoryActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.permission.PermissionHelper;
import com.heba.popupwindow.BusinessAddressEditPopupWindow;
import com.heba.popupwindow.ShopAddressPopupWindow;
import com.heba.popupwindow.callback.EditAddressClickListener;
import com.heba.utils.GlideUtil;
import com.heba.utils.IndicatorLineUtil;
import com.heba.view.ClearEditTextView;
import com.heba.view.Loading;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import easypermission.EasyPermission;
import easypermission.GrantResult;
import easypermission.Permission;
import easypermission.PermissionRequestListener;

public class ShopListFragment extends BaseFragment {
    private LocationListener gpsLocationListener;
    private LocationListener networkListener;
    private LocationManager locationManager;
    private Location mLocation;

    /**
     * 監聽gps和network
     */
    private ClearEditTextView clearEditTextView;
    private ConstraintLayout bottomLine1;
    private String[] tabStrings;
    private TabLayout tabLayout;
    private ViewPager shopViewPager;
    private ShopNearbyPriceFragment nearbyFragement;
    private ShopNearbyPriceFragment priceFragment;
    private List<Fragment> fragments = new ArrayList<>();
    private List<UserAddressObject> addressObjectList = new ArrayList<>();
    private UserAddressObject selectAddressObject ;
    private ConstraintLayout topBar;
    private int selectIndex = 0;


    private ConstraintLayout img_right;

    private ShopAddressPopupWindow editPopupWindow;
    private FmPagerAdapter shopAdapter;
    protected MyProgressDialog progressDialog;
    protected Loading loading;
    private TextView address_text;
    private TextView alert_text_view;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.shop_fragement, container, false);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initView(view);
        getAddressList();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    public void initView(View view) {

        topBar = view.findViewById(R.id.add_view);
        tabLayout = view.findViewById(R.id.diary_tabLayout);
        shopViewPager = view.findViewById(R.id.shop_viewpager);
        address_text = view.findViewById(R.id.address_text);
        alert_text_view = view.findViewById(R.id.alert_text_view);
        alert_text_view.setVisibility(View.GONE);
        nearbyFragement = new ShopNearbyPriceFragment();
        nearbyFragement.type = 0;
        priceFragment = new ShopNearbyPriceFragment();
        priceFragment.type = 1;
        tabStrings = getActivity().getResources().getStringArray(R.array.array_shop_home);
        fragments.add(nearbyFragement);
        fragments.add(priceFragment);
        img_right = view.findViewById(R.id.img_right);
        shopAdapter = new FmPagerAdapter(fragments,getFragmentManager());
        shopViewPager.setAdapter(shopAdapter);
        shopViewPager.setOffscreenPageLimit(2);
        progressDialog =new MyProgressDialog(getContext(), getResources().getString(R.string.loading));
        for (int i = 0; i < tabStrings.length; i++) {
            tabLayout.addTab(tabLayout.newTab());
        }
        tabLayout.setupWithViewPager(shopViewPager);
        for (int i = 0 ;i<tabStrings.length;i++){
            tabLayout.getTabAt(i).setText(tabStrings[i]);
        }
        tabLayout.getTabAt(0).select();
        bottomLine1 = view.findViewById(R.id.bottom_line_1);
        /**
         * 设置指示线长度间隔(单位dp)
         */
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                IndicatorLineUtil.setIndicator(tabLayout, 0, 0);
            }
        });
        TextView title = (TextView) (((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(0)).getChildAt(1));
        title.setTextAppearance(R.style.TabLayoutSelectedTextStyle1);
        /**
         * tabLayout监听滑动指示卡
         */
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tabLayout.getSelectedTabPosition();
                Resources resources = getResources();
                DisplayMetrics dm = resources.getDisplayMetrics();
                TextView title = (TextView) (((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(tab.getPosition())).getChildAt(1));
                title.setTextAppearance(R.style.TabLayoutSelectedTextStyle1);
                int width3 = dm.widthPixels;
                TranslateAnimation translateAnimation1 = new TranslateAnimation((selectIndex)*(width3/2),(position)*(width3/2),0,0);
                translateAnimation1.setDuration(300);
                translateAnimation1.setFillEnabled(true);//使其可以填充效果从而不回到原地
                translateAnimation1.setFillAfter(true);//不回到起始位置
                bottomLine1.startAnimation(translateAnimation1);


                translateAnimation1.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        selectIndex = tabLayout.getSelectedTabPosition();

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView title = (TextView) (((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(tab.getPosition())).getChildAt(1));
                title.setTextAppearance(R.style.TabLayoutNormalTextStyle1);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        clearEditTextView = view.findViewById(R.id.clearEditText);
        clearEditTextView.setTextHint(getActivity().getResources().getString(R.string.product_category));


        //点击edittex跳转
        clearEditTextView.clearFocus();
        clearEditTextView.setOnEditTextListener(new ClearEditTextView.OnEditTextListener() {
            @Override
            public void onDeleteClick() {

            }

            @Override
            public void afterTextChanged(String text) {

            }

            @Override
            public void onSearchClick(String text) {

            }

            @Override
            public void onIntent() {
                openActivity(ItemProductCategoryActivity.class);
            }
        });
        editPopupWindow = new ShopAddressPopupWindow(getContext(), ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        editPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        editPopupWindow.shopListFragment = this;
        editPopupWindow.setClickListener(new EditAddressClickListener() {
            @Override
            public void clickRowToSelect(UserAddressObject object) {
                new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                    @Override
                    public void Success() {

                        for (int i = 0 ; i < addressObjectList.size();i++){
                            UserAddressObject obj = addressObjectList.get(i);
                            if (obj.getAddressId() == object.getAddressId()){
                                obj.setIsSelected("1");

                                address_text.setText(obj.getDistrict()+obj.getStreet()+obj.getEstate()+obj.getBuilding()+obj.getFloor()+obj.getUnit());
                                getAddressList();
                                break;
                            }
                        }
//                        MessageEvent event = new MessageEvent();
//                        event.setEvent(CommonConfig.UPDATE_LOCATION);
//                        EventBus.getDefault().post(event);
                        editPopupWindow.dismiss();
                        editPopupWindow.cycle_imageview.setImageResource(R.drawable.guide_point_normal);

                    }

                    @Override
                    public void Fail(String error) {

                    }
                }).selectShopAddress(getContext(),object.getAddressId());
            }

            @Override
            public void clickAddNewAddress() {
                ///跳轉到添加新地址界面
                Bundle bundle = new Bundle();
                if (mLocation!=null){
                    bundle.putDouble("lat",mLocation.getLatitude());
                    bundle.putDouble("lng",mLocation.getLongitude());
                }else{
                    bundle.putDouble("lat",0);
                    bundle.putDouble("lng",0);
                }
                bundle.putString("type","1");


                openActivity(BusinessAddNewAddressActivity.class,bundle);

            }

            @Override
            public void clickEditAddress(UserAddressObject object) {

                Bundle bundle = new Bundle();

                bundle.putSerializable("USER_ADDRESS_OBJECT",object);

                openActivity(BusinessEditAddressActivity.class,bundle);
            }
        });
        topBar.setOnClickListener(v -> {
            editPopupWindow.list = addressObjectList;
            editPopupWindow.showAtLocation(img_right, Gravity.BOTTOM,0,0);
        });
        img_right.setOnClickListener(v->{
            openActivity(ScanActivity.class,null);
        });
        editPopupWindow.constrain_layout.setOnClickListener(v->{
            for (int i = 0;i<addressObjectList.size();i++){
                UserAddressObject dataObj = addressObjectList.get(i);
                dataObj.setIsSelected("0");
            }
            getLocationData();
            editPopupWindow.cycle_imageview.setImageResource(R.drawable.guide_point_green);
            editPopupWindow.setList(addressObjectList);
            editPopupWindow.dismiss();

            address_text.setText(getResources().getString(R.string.now_location));


        });

    }

    public void getAddressList() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);

        params.put("BuddyUserID",Cfg.UserID);
        params.put("UserID",Cfg.UserID);
        params.put("Type","1");
        alert_text_view.setVisibility(View.INVISIBLE);
        shopViewPager.setVisibility(View.VISIBLE);
        client.get(Cfg.BaseUrl + "/User/GetUserAddressInfo", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getContext()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();;
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");

                            if (array.length() > 0) {
                                List<UserAddressObject> list = new Gson().fromJson(array.toString(), new TypeToken<List<UserAddressObject>>() {
                                }.getType());
                                addressObjectList.clear();
                                addressObjectList.addAll(list);
                                for (int i = 0;i<addressObjectList.size();i++){
                                    UserAddressObject dataObj = addressObjectList.get(i);
                                    if(dataObj.getIsSelected().equals("1")){
                                        address_text.setText(dataObj.getDistrict()+dataObj.getStreet()+dataObj.getEstate()+dataObj.getBuilding()+","+dataObj.getFloor()+getString(R.string.Floor)+","+dataObj.getUnit()+getString(R.string.Unit));
                                        nearbyFragement.lat = Double.parseDouble(dataObj.getLat());
                                        nearbyFragement.lng = Double.parseDouble(dataObj.getLng());
                                        priceFragment.lat = Double.parseDouble(dataObj.getLat());
                                        priceFragment.lng = Double.parseDouble(dataObj.getLng());
                                        nearbyFragement.refreshShopList();
                                        priceFragment.refreshShopList();
                                    }
                                }

                            }else{
                                getLocationData();
                                editPopupWindow.cycle_imageview.setImageResource(R.drawable.guide_point_green);
                            }
                            editPopupWindow.setList(addressObjectList);
                            editPopupWindow.recycleAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }

                    public void Failure() {
                        super.Failure();

                        progressDialog.dismiss();

                    }

                });
    }
    private void getLocationData() {
//        EasyPermission.with(getActivity())
//                .addPermissions(Permission.Group.LOCATION)      //申请定位权限组
//                .request(new PermissionRequestListener() {
//                    @Override
//                    public void onGrant(Map<String, GrantResult> result) {
//                        System.out.println("111111111111111111");
//                        System.out.println(result);
//
//                    }
//
//                    @Override
//                    public void onCancel(String stopPermission) {
//                        //在addRequestPermissionRationaleHandler的处理函数里面调用了NextAction.next(NextActionType.STOP,就会中断申请过程，直接回调到这里来
//                    }
//
//                });

        new PermissionHelper(getContext(), new PermissionHelper.PermissionListener() {
            @Override
            public void onPermissionSuccess() {

                alert_text_view.setVisibility(View.INVISIBLE);
                shopViewPager.setVisibility(View.VISIBLE);
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);//高精度
                criteria.setAltitudeRequired(false);//无海拔要求   criteria.setBearingRequired(false);//无方位要求
                criteria.setCostAllowed(true);//允许产生资费   criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
                locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
                // 获取最佳服务对象
                String provider = locationManager.getBestProvider(criteria, true);


                networkListener = new LocationListener() {

                    @Override
                    public void onLocationChanged(Location location) {

                        mLocation = location;
                        locationManager.removeUpdates(this);
                        locationManager.removeUpdates(gpsLocationListener);
                        if (mLocation != null) {
                            nearbyFragement.lat = mLocation.getLatitude();
                            nearbyFragement.lng = mLocation.getLongitude();
                            priceFragment.lat =  mLocation.getLatitude();
                            priceFragment.lng = mLocation.getLongitude();
                            nearbyFragement.refreshShopList();
                            priceFragment.refreshShopList();
                        }

                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {

                    }

                    @Override
                    public void onProviderEnabled(String provider) {
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                        String string = provider;
                        System.out.println(provider);
                    }

                };
                gpsLocationListener = new LocationListener() {

                    @Override
                    public void onLocationChanged(Location location) {

                        locationManager.removeUpdates(networkListener);
                        mLocation = location;
                        if (mLocation != null) {

                            nearbyFragement.lat = mLocation.getLatitude();
                            nearbyFragement.lng = mLocation.getLongitude();
                            priceFragment.lat =  mLocation.getLatitude();
                            priceFragment.lng = mLocation.getLongitude();
                            nearbyFragement.refreshShopList();
                            priceFragment.refreshShopList();
                        }
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                    }

                    @Override
                    public void onProviderEnabled(String provider) {
                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {

                    }
                };

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10, gpsLocationListener);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10, networkListener);
                locationManager.getLastKnownLocation(provider);
            }

            @Override
            public void onPermissionFailure() {
                alert_text_view.setVisibility(View.VISIBLE);
                shopViewPager.setVisibility(View.INVISIBLE);
            }
        }).requestPermission(com.yanzhenjie.permission.Permission.Group.LOCATION);


    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals(CommonConfig.UPDATE_ADDRESS_LIST)) {
            getAddressList();
        }
        if(event.getEvent().equals(CommonConfig.UPDATE_SHOP_LIST)){
            nearbyFragement.refreshShopList();
            priceFragment.refreshShopList();
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ShopListEvent event){
        if (event.getEvent().equals(CommonConfig.UPDATE_ADDRESS_LIST)) {
            getAddressList();
        }
        if(event.getEvent().equals(CommonConfig.UPDATE_SHOP_LIST)){
            nearbyFragement.refreshShopList();
            priceFragment.refreshShopList();
        }
    }


    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
}
